package com.school.platform.servlet;

import com.school.platform.utils.DBConnectionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html; charset=UTF-8"); // 替换原来的 text/plain
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8"); // 解决 POST 请求参数乱码

        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            response.getWriter().write("not_logged_in");
            return;
        }

        int infoId = Integer.parseInt(request.getParameter("infoId"));
        String content = request.getParameter("content");

        try (Connection connection = DBConnectionUtil.getConnection()) {
            String sql = "INSERT INTO comments (info_id, user_id, content) VALUES (?, ?, ?)";
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                preparedStatement.setInt(1, infoId);
                preparedStatement.setInt(2, userId);
                preparedStatement.setString(3, content);
                int rowsAffected = preparedStatement.executeUpdate();
                if (rowsAffected > 0) {
                    response.getWriter().write("success");
                } else {
                    response.getWriter().write("error");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("error");
        }
    }
}